package com.dms.modules.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dms.modules.product.entity.Product;
import com.dms.modules.product.service.ProductService;
import com.dms.modules.product.service.ProductCategoryService;
import com.dms.modules.user.entity.UserBrowseHistory;
import com.dms.modules.user.mapper.UserBrowseHistoryMapper;
import com.dms.modules.user.service.UserBrowseHistoryService;
import com.dms.modules.user.vo.UserBrowseHistoryVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import lombok.extern.slf4j.Slf4j;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
public class UserBrowseHistoryServiceImpl extends ServiceImpl<UserBrowseHistoryMapper, UserBrowseHistory> implements UserBrowseHistoryService {

    @Autowired
    private ProductService productService;

    @Autowired
    private ProductCategoryService categoryService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addBrowseHistory(Long userId, Long productId, Long categoryId, Integer stayDuration) {
        // 查询是否存在浏览记录
        UserBrowseHistory history = lambdaQuery()
                .eq(UserBrowseHistory::getUserId, userId)
                .eq(UserBrowseHistory::getProductId, productId)
                .one();
        
        LocalDateTime now = LocalDateTime.now();
        
        if (history != null) {
            // 更新浏览记录
            history.setViewCount(history.getViewCount() + 1);
            history.setLastViewTime(now);
            if (stayDuration != null) {
                history.setStayDuration(history.getStayDuration() + stayDuration);
            }
            return updateById(history);
        } else {
            // 创建新的浏览记录
            history = new UserBrowseHistory();
            history.setUserId(userId);
            history.setProductId(productId);
            history.setCategoryId(categoryId);
            history.setViewCount(1);
            history.setStayDuration(stayDuration != null ? stayDuration : 0);
            history.setLastViewTime(now);
            history.setCreateTime(now);
            history.setUpdateTime(now);
            return save(history);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteProductBrowseHistory(Long userId, Long productId) {
        return lambdaUpdate()
                .eq(UserBrowseHistory::getUserId, userId)
                .eq(UserBrowseHistory::getProductId, productId)
                .remove();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean clearBrowseHistory(Long userId) {
        return lambdaUpdate()
                .eq(UserBrowseHistory::getUserId, userId)
                .remove();
    }

    @Override
    public IPage<UserBrowseHistory> list(Page<UserBrowseHistory> page, Long userId, Long categoryId) {
        try {
            LambdaQueryWrapper<UserBrowseHistory> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(UserBrowseHistory::getUserId, userId);
            
            // 只有当categoryId有效时才添加分类过滤条件
            if (categoryId != null && categoryId > 0) {
                wrapper.eq(UserBrowseHistory::getCategoryId, categoryId);
            }
            
            wrapper.orderByDesc(UserBrowseHistory::getLastViewTime);
            return page(page, wrapper);
        } catch (Exception e) {
            log.error("获取用户浏览历史失败: userId={}, categoryId={}", userId, categoryId, e);
            // 返回空数据而不是抛出异常
            return new Page<>(page.getCurrent(), page.getSize());
        }
    }

    @Override
    public IPage<UserBrowseHistoryVO> listWithProductInfo(Page<UserBrowseHistory> page, Long userId, Long categoryId) {
        try {
            // 1. 获取浏览历史基本数据
            IPage<UserBrowseHistory> historyPage = list(page, userId, categoryId);
            
            // 2. 转换为VO对象
            List<UserBrowseHistoryVO> voList = new ArrayList<>();
            
            if (historyPage.getRecords() != null && !historyPage.getRecords().isEmpty()) {
                // 获取所有商品ID
                List<Long> productIds = historyPage.getRecords().stream()
                        .map(UserBrowseHistory::getProductId)
                        .collect(Collectors.toList());
                
                // 批量查询商品信息
                Map<Long, Product> productMap = productService.listByIds(productIds).stream()
                        .collect(Collectors.toMap(Product::getId, product -> product));
                
                // 转换为VO
                for (UserBrowseHistory history : historyPage.getRecords()) {
                    UserBrowseHistoryVO vo = new UserBrowseHistoryVO();
                    BeanUtils.copyProperties(history, vo);
                    
                    // 设置商品信息
                    Product product = productMap.get(history.getProductId());
                    if (product != null) {
                        vo.setProductName(product.getName());
                        vo.setProductImage(product.getMainImage());
                        vo.setProductPrice(product.getPrice());
                        vo.setProductDescription(product.getDetail());
                        vo.setCategoryId(product.getCategoryId());
                        
                        // 获取分类名称
                        if (product.getCategoryId() != null) {
                            vo.setCategoryName(categoryService.getById(product.getCategoryId()).getName());
                        }
                    }
                    
                    voList.add(vo);
                }
            }
            
            // 3. 创建新的分页对象
            Page<UserBrowseHistoryVO> voPage = new Page<>(page.getCurrent(), page.getSize(), historyPage.getTotal());
            voPage.setRecords(voList);
            
            return voPage;
        } catch (Exception e) {
            log.error("获取用户浏览历史(含商品信息)失败: userId={}, categoryId={}", userId, categoryId, e);
            return new Page<>(page.getCurrent(), page.getSize());
        }
    }
} 